import { AxiosInstance, CreateAxiosDefaults } from "axios";
import { base } from "./base";
import { useUserStore } from "@ui/vue/store";
import { router, routerTo } from "@ui/vue/router";
const INSTACE = base('../'), CONFIG_URL = '/public/config/server.json'
  , INSTACE_OBJ: any = {}, HOST = location.host
let config: any, configPromise: Promise<any>
function getConfigV(name?: string): any {
  return name ? config[name] : config
}
function dealUrl(arr: any = '', def: string = ''): string {
  arr = arr.servers || arr
  if (typeof arr === 'object') {
    return arr.filter((it: string) => it.indexOf(HOST) != -1)[0] || arr[0] || def
  }
  return arr || def
}
export function localGet(url: string, params: any = { version: new Date().getTime() }, data: any = {}) {
  return INSTACE.get(url, { data, params }).then(res => {
    return res.data
  })
}
export function localPost(url: string, data: any = {}, params: any = {}) {
  return INSTACE.post(url, { data, params }).then(res => {
    return res.data
  })
}
export function getConfig(name?: string) {
  if (config) {
    return Promise.resolve(getConfigV(name))
  }
  if (!configPromise) {
    configPromise = localGet(CONFIG_URL).then(res => {
      config = res
      const store = useUserStore(), user = store.getUser
      if (!user) {
        store.setUser(config.magicUser)
        if (routerTo) {
          router.replace(routerTo)
        }
      }
    })
  }
  return configPromise.then(() => getConfigV(name))
}
export function getInstace(name: string = 'baseUrl', config?: CreateAxiosDefaults): Promise<AxiosInstance> {
  if (!INSTACE_OBJ[name]) {
    INSTACE_OBJ[name] = getConfig().then(res => {
      const url = dealUrl(res[name], res.defaultUrl).trim()
      return base(url, config)
    })
  }
  return INSTACE_OBJ[name]
}